package com.study.notepad.service.impl;/*
 @Author Cedar
 @DESCRIPTION 
*/

import com.study.notepad.bean.User;
import com.study.notepad.dao.UserDao;
import com.study.notepad.service.UserService;
import com.study.notepad.util.RandomValueUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDao();

    @Override
    public User findUserById(Integer id) {
        return userDao.queryById(id);
    }

    @Override
    public User login(String userName, String password) {
        User user = userDao.queryByUserName(userName);
        if (user != null) {
            String passwordTrue = user.getPassword();
            String salt = user.getSalt();
            String passwordMd5 = DigestUtils.md5Hex(password + salt);
            if (passwordTrue.equals(passwordMd5)) {
                user.setPassword("true");
            } else {
                user.setPassword("false");
            }
        }
        return user;
    }

    @Override
    public int register(String userName, String password, String headImg) {
        String salt = RandomValueUtil.randomString(5);
        password = DigestUtils.md5Hex(password + salt);
        return userDao.insert(userName, password, headImg, salt);
    }

    @Override
    public User findUserByName(String userName) {
        return userDao.queryByUserName(userName);
    }

    @Override
    public int updateUser(Integer id, String userName, String password, String headImg) {
        User userById = findUserById(id);
        String userNameOld = userById.getName();
        String passwordOld = userById.getPassword();
        String headImgOld = userById.getHeadImg();

        if (StringUtils.isBlank(userName)) {
            userName = userNameOld;
        } else if (!userName.equals(userNameOld)) {
            User userByName = findUserByName(userName);
            if (userByName != null) {
                return -1;
            }
        }
        if (StringUtils.isNotBlank(password) && !password.equals(passwordOld)) {
            String salt = userById.getSalt();
            password = DigestUtils.md5Hex(password + salt);
        } else {
            password = passwordOld;
        }

        if (StringUtils.isBlank(headImg)) {
            headImg = headImgOld;
        }

        return userDao.updateById(id, userName, password, headImg);
    }
}
